import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { imStore, userStore } from "@/store/index"; // 导入IM MobX Store
import { IConversation } from "@/type/index"; // 导入会话类型
import md5 from "@/util/md5.min.js"; // 导入 MD5 工具

// 获取当前用户的UID（假设已登录且存储在 wx.getStorageSync 中）
const myCurrentUid = userStore.userInfo.uid;

/**
 * 根据 from_uid 和 to_uid 计算会话 ID
 * @param uid1 用户UID1
 * @param uid2 用户UID2
 * @returns 会话 ID (md5 加密字符串)
 */
function getConversationId(uid1: string, uid2: string): string {
  // 确保 uid 数组按字典序排序
  const uids = [uid1, uid2].sort();
  // 计算 MD5
  return md5(uids.join(","));
}

Page({
  behaviors: [storeBindingsBehavior],

  data: {
    triggered: false, // 下拉刷新状态，控制 refresher 的显示与隐藏
    // 固定的虚拟用户会话列表
    fixedVirtualConversations: [
      // 这里的 conversation_id, unreadCount, lastMessage 等需要根据实际情况初始化
      // 如果后端不为虚拟用户返回会话，这些值可能需要前端模拟或初始化为0/null
      {
        peer_uid: "system_notice_id", // 约定系统通知的UID
        peer_nickname: "系统通知",
        peer_avatar: "/static/images/message/system.png", // 自定义虚拟用户头像
        isSystemConversation: true,
        isVirtualPeer: true,
        conversation_id: getConversationId(myCurrentUid, "system_notice_id"), // 假设虚拟用户会话ID也按此规则
        unreadCount: 0, // 初始未读数，会通过 fetchUnreadCounts 更新
        updateTime: Date.now(), // 初始更新时间，会通过 fetchConversationList/lastMessage 更新
        lastMessage: {
          // 模拟最后一条消息
          msg_id: "sys_last_msg_1",
          conversation_id: getConversationId(myCurrentUid, "system_notice_id"),
          from_uid: "system_notice_id",
          to_uid: myCurrentUid,
          type: "text",
          body: "欢迎使用系统通知！",
          createTime: Date.now(),
          status: "success",
          isMyMessage: false,
        },
      },
      {
        peer_uid: "order_message_id", // 约定订单消息的UID
        peer_nickname: "订单消息",
        peer_avatar: "/static/images/message/order.png",
        isSystemConversation: true,
        isVirtualPeer: true,
        conversation_id: getConversationId(myCurrentUid, "order_message_id"),
        unreadCount: 0,
        updateTime: Date.now(),
        lastMessage: {
          msg_id: "order_last_msg_1",
          conversation_id: getConversationId(myCurrentUid, "order_message_id"),
          from_uid: "order_message_id",
          to_uid: myCurrentUid,
          type: "text",
          body: "您的订单已发货！",
          createTime: Date.now(),
          status: "success",
          isMyMessage: false,
        },
      },
      {
        peer_uid: "ad_message_id", // 约定广告消息的UID
        peer_nickname: "广告消息",
        peer_avatar: "/static/images/message/info.png",
        isSystemConversation: true,
        isVirtualPeer: true,
        conversation_id: getConversationId(myCurrentUid, "ad_message_id"),
        unreadCount: 0,
        updateTime: Date.now(),
        lastMessage: {
          msg_id: "ad_last_msg_1",
          conversation_id: getConversationId(myCurrentUid, "ad_message_id"),
          from_uid: "ad_message_id",
          to_uid: myCurrentUid,
          type: "text",
          body: "最新优惠活动来袭！",
          createTime: Date.now(),
          status: "success",
          isMyMessage: false,
        },
      },
    ] as IConversation[],
  },

  // 绑定MobX Store
  storeBindings: {
    store: imStore,
    fields: [
      "conversationList", // 绑定会话列表
      "totalUnreadCount", // 绑定总未读数
      "isFetchingConversations", // 绑定会话加载状态
    ],
  },

  onLoad() {
    if (!myCurrentUid) {
      wx.showToast({ title: "用户未登录，请先登录", icon: "none" });
      // 可以在这里跳转到登录页
      return;
    }
    // 首次加载数据
    this.refreshData();
  },

  onShow() {
    // 页面显示时，重新拉取会话列表和未读数，不再轮询
  },
  onHide() {
    // 页面隐藏时，不再需要停止轮询
  },
  onUnload() {
    // 页面卸载时，不再需要停止轮询
  },
  // 刷新所有相关数据 (会话列表和未读数)
  async refreshData(refresh: boolean = true) {
    try {
      await imStore.fetchConversationList(refresh); // 刷新或加载会话列表
      await imStore.fetchUnreadCounts(); // 获取未读数，MobX Store 会更新到 conversationList 中

      // 同步虚拟会话的未读数和最新消息
      const updatedFixedConversations = this.data.fixedVirtualConversations.map(
        (fixedConv) => {
          const foundConv = imStore.conversationList.find(
            (c) => c.conversation_id === fixedConv.conversation_id
          );
          if (foundConv) {
            return {
              ...fixedConv,
              unreadCount: foundConv.unreadCount,
              lastMessage: foundConv.lastMessage || fixedConv.lastMessage,
              updateTime: foundConv.updateTime || fixedConv.updateTime,
            };
          }
          return fixedConv;
        }
      );
      this.setData({ fixedVirtualConversations: updatedFixedConversations });
    } catch (error) {
      console.error("Data refresh failed:", error);
      wx.showToast({ title: "数据加载失败", icon: "none" });
    } finally {
      wx.hideLoading();
    }
  },

  // 下拉刷新事件处理
  async onRefresh() {
    this.setData({ triggered: true });
    await this.refreshData(true);
    this.setData({ triggered: false });
  },

  // 上拉触底加载更多事件处理
  onReachBottom() {
    if (!this.data.isFetchingConversations) {
      imStore.fetchConversationList(false); // 加载更多（refresh参数为false）
    }
  },

  // 跳转到聊天页面
  gotoChat(e: WechatMiniprogram.TouchEvent) {
    const conversation: IConversation = e.currentTarget.dataset.conversation;

    // 清除该会话的未读数 (在进入聊天页面之前清除，以便页面加载时是已读状态)
    if (conversation.unreadCount > 0) {
      imStore.clearConversationUnreadCount(conversation.conversation_id);
    }
    this.requestSubscriptionMessage();
    const contactStr = encodeURIComponent(
      JSON.stringify(conversation.peerContact)
    );
    // 传递所有必要参数给聊天页面
    wx.navigateTo({
      url: `../im/index?conversationId=${conversation.conversation_id}&peerId=${
        conversation.peer_uid
      }&peerNickname=${encodeURIComponent(
        conversation.peer_nickname
      )}&peerAvatar=${encodeURIComponent(
        conversation.peer_avatar
      )}&isBlockedByMe=${conversation.isBlockedByMe || false}&isVirtualPeer=${
        conversation.isVirtualPeer || false
      }&peerContact=${contactStr}`,
    });
  },

  // 格式化时间戳，使其更友好地显示 (保持不变)
  formatTime(timestamp: number): string {
    if (!timestamp) return "";

    const date = new Date(timestamp);
    const now = new Date();

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");

    const isToday =
      date.getDate() === now.getDate() &&
      date.getMonth() === now.getMonth() &&
      date.getFullYear() === now.getFullYear();

    if (isToday) {
      return `${hours}:${minutes}`;
    }

    const yesterday = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate() - 1
    );
    const isYesterday =
      date.getDate() === yesterday.getDate() &&
      date.getMonth() === yesterday.getMonth() &&
      date.getFullYear() === yesterday.getFullYear();

    if (isYesterday) {
      return `昨天 ${hours}:${minutes}`;
    }

    const isSameYear = date.getFullYear() === now.getFullYear();
    if (isSameYear) {
      return `${month}-${day}`;
    }

    return `${year}-${month}-${day}`;
  },

  // 请求订阅消息权限 (保持不变)
  async requestSubscriptionMessage() {
    // const templateIds = [
    //   'rJBXad410F5_6YSAsXfCe9JLIvagBYCfzYN6sqMGJTY'
    // ];
    // await wx.requestSubscribeMessage({
    //   tmplIds: templateIds,
    // });
  },
});
